/**
  @authoer: lss
  @date: 2021/3/5
  @note:
**/
package common

import (
	"errors"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/validation"
	"reflect"
	"strings"
)

func VerifyForm(obj interface{}, lan string) error {
	setVerifyMessage(lan)
	valid := validation.Validation{}
	b, err := valid.Valid(obj)
	if err != nil {
		return err
	}
	if !b {
		arr := strings.Split(valid.Errors[0].Key, ".") //切分例如Password.MinSize

		st := reflect.TypeOf(obj).Elem() // 反射获取 input 信息

		field, _ := st.FieldByName(arr[0]) // 获取 Password 参数信息
		if lan == "eng" {
			logs.Error(errors.New(field.Tag.Get("eng") + strings.Split(valid.Errors[0].Message, " ")[1]))
			return errors.New(field.Tag.Get("eng") + strings.Split(valid.Errors[0].Message, " ")[1])
		} else {
			logs.Error(errors.New(field.Tag.Get("chn") + strings.Split(valid.Errors[0].Message, " ")[1]))
			return errors.New(field.Tag.Get("chn") + strings.Split(valid.Errors[0].Message, " ")[1])
		}
	}
	return nil
}

func CheckId(id uint64) bool {
	if id < 100000000 || id > 999999999 {
		return false
	}
	return true
}

// 设置表单验证messages
func setVerifyMessage(lan string) {
	var MessageTmpls = map[string]string{

		"Required": "不能为空",

		"Min": "最小值为%d",

		"Max": "最大值为%d",

		"Range": "范围为%d到%d",

		"MinSize": "最短长度为%d",

		"MaxSize": "最大长度为%d",

		"Length": "长度必须为%d",

		"Alpha": "必须是有效的字母",

		"Numeric": "必须是有效的数字",

		"AlphaNumeric": "必须是有效的字母或数字",

		"Match": "必须匹配%s",

		"NoMatch": "必须不匹配%s",

		"AlphaDash": "必须是有效的字母、数字或连接符号(-_)",

		"Email": "必须是有效的电子邮件地址",

		"IP": "必须是有效的IP地址",

		"Base64": "必须是有效的base64字符",

		"Mobile": "必须是有效的手机号码",

		"Tel": "必须是有效的电话号码",

		"Phone": "必须是有效的电话或移动电话号码",

		"ZipCode": "必须是有效的邮政编码",
	}
	if lan == "eng" {
		validation.SetDefaultMessage(validation.MessageTmpls)
	} else {
		validation.SetDefaultMessage(MessageTmpls)
	}

}
